import { Col, Row } from 'antd';
import { connect } from 'dva';
import uuid from 'es6-uuid';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

import { TableC, SecondHeaderC, IconC } from '@/src/comps';

import styles from './index.less';
import LeftCharts from './LeftCharts';

let myObserver = null;
// eslint-disable-next-line react/no-redundant-should-component-update
class ProductNumScaleC extends PureComponent {
  constructor() {
    super();
    this.state = {
      targetTableHeight: 515,
      dataSource: [],
      // 默认定位在产品数量 true的峰值上 , 产品规模false
      columnOneOrTwo: true,
      xAxis1: [],
      yAxis1: [
        // y轴信息
        { name: '产品数量', gridIndex: 0 },
        { name: '产品规模(亿元)', gridIndex: 1 },
      ],
      series1: [],
      currentDate: '', // 当前时间
    };
  }

  // 左侧charts
  getLeftCharts = (nextProps) => {
    const { dispatch, args, timestamp } = nextProps;
    dispatch({
      type: 'organProductAnalysisM/getLeftChartsInfo',
      payload: {
        timestamp,
        startDate: moment(args.startDate).format('YYYY-MM-DD'),
        endDate: moment(args.endDate).format('YYYY-MM-DD'),
        tenantId: args.tenantId,
      },
      callback: (info) => {
        const copySeriesInfo = _.cloneDeep(info.series);
        const xAxisCopy = _.cloneDeep(info.xAxis);
        let productData;
        copySeriesInfo.map((v) => {
          if (v.name === '产品数量') {
            productData = v.data;
            v.type = 'line';
            v.xAxisIndex = 0;
            v.yAxisIndex = 0;
          }
          if (v.name === '产品规模') {
            v.type = 'line';
            v.xAxisIndex = 1;
            v.yAxisIndex = 1;
          }
        });
        this.setState({
          xAxis1: info.xAxis,
          series1: copySeriesInfo,
        });
        // 取最大值对应的时间
        const max = Math.max(...productData);
        const index = productData.map((v) => v).indexOf(max);
        // 默认定位在产品数量的峰值上
        this.getRightData({
          type: 'scale',
          date: xAxisCopy[index],
        });
        // 设置当前事件state
        this.setState({
          currentDate: xAxisCopy[index],
        });
      },
    });
  };

  windowChange = () => {
    const { dataSource } = this.state;
    if (dataSource.length === 10) this.getTableHeight();
  };

  componentDidMount() {
    this.getLeftCharts(this.props);
    // 监听窗口变化
    window.addEventListener('resize', this.windowChange);
    myObserver = new ResizeObserver((entries) => {
      entries.forEach(() => {
        this.windowChange();
      });
    });
    myObserver.observe(document.getElementById('tableid'));
    this.getTableHeight();
  }

  getTableHeight = () => {
    const tableHead = document.querySelector('#tableid .ant-table-thead');
    const tableBody = document.querySelector('#tableid .ant-table-tbody');

    const targetTableHeight = tableBody?.clientHeight + tableHead?.clientHeight + 1 + 24; // 24为列表上方时间的高度， 1为可视边框
    this.setState({
      targetTableHeight,
    });
    // if (tableBody?.clientHeight && tableHead?.clientHeight) {
    //   this.timerId = setInterval(() => {
    //     const targetTableHeight = tableBody?.clientHeight + tableHead?.clientHeight + 1 + 24; // 24为列表上方时间的高度， 1为可视边框
    //     if (tableBody.clientHeight !== 0) clearInterval(this.timerId);
    //     this.setState({
    //       targetTableHeight,
    //     });
    //   }, 1000);
    // }
  };

  componentWillUnmount() {
    clearInterval(this.timerId);
  }

  // eslint-disable-next-line react/no-deprecated
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { args, timestamp } = nextProps;
    if (JSON.stringify(args) !== JSON.stringify(this.props.args) || timestamp !== this.props.timestamp) {
      this.getLeftCharts(nextProps);
    }
  }

  // 获得右侧
  getRightData = (par) => {
    const { date, type } = par;
    const {
      dispatch,
      args: { tenantId },
    } = this.props;
    dispatch({
      type: 'organProductAnalysisM/getResultList',
      payload: { date, type, tenantId },
      callback: (dataSource) => {
        // 取前10
        let data = _.cloneDeep(dataSource);
        if (data.length > 10) {
          data = data.slice(0, 10);
        }
        this.setState({
          dataSource: data,
        });
      },
    });
  };

  /**
   * 设置column
   * @param {boolean} columnOneOrTwo
   */
  setColumn = (columnOneOrTwo) => {
    this.setState({
      columnOneOrTwo,
    });
  };

  /**
   * 点击左侧
   * @param par {*} 右侧查询参数
   * @param e {*} 点击事件event
   */
  clickProps = (par) => {
    this.getRightData(par);
    // 设置当前事件state
    this.setState({
      currentDate: par.date,
    });
  };

  render() {
    const {
      organProductAnalysisM: { columns, column1 },
      loading, // 产品数量columns, 产品规模column1
    } = this.props;
    const { dataSource, columnOneOrTwo } = this.state;
    return (
      <div className={styles.productScale}>
        <SecondHeaderC title='产品数量和规模走势图' />
        <div className={styles.icon}>
          <IconC title='展示指定时间区间和指定租户的总产品数量（存续和清算中产品）和规模' type='info' />
        </div>
        <div style={{ marginTop: '10px' }}>
          <Row gutter={16}>
            <Col span={16}>
              <LeftCharts
                clickProps={this.clickProps}
                xAxis1={this.state.xAxis1 || []}
                series1={this.state.series1 || []}
                yAxis1={this.state.yAxis1 || []}
                dataSource={dataSource}
                targetTableHeight={this.state.targetTableHeight}
                setColumn={this.setColumn}
              />
            </Col>
            <Col span={8}>
              <div id='tableid'>
                <div style={{ fontSize: 14, height: 24, fontWeight: 'bold' }}>{this.state.currentDate}</div>
                <TableC
                  selfScrollY
                  columns={columnOneOrTwo ? columns : column1 || []}
                  dataSource={dataSource || []}
                  scroll={{ x: 'max-content', y: 515 }}
                  rowKey={`id_${uuid(4)}`}
                  hidePage
                  size='small'
                  loading={loading.effects[`organProductAnalysisM/getResultList`]}
                />
              </div>
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}
export default connect(({ organProductAnalysisM, loading }) => ({
  organProductAnalysisM,
  loading,
}))(ProductNumScaleC);
